function ltable(tab,names,header,path)
% Function that generates LaTeX tables

% Variables:
% tab		table with data
% names		array (n x 4) with ({'1','0'} = {Variable,Midheader}, variable name in input table, variable or midheader name in LaTeX table, precision}
% header	names to be put in the header
% path		where to save figure

% Create file
	fid = fopen(path ,'w');

% Number of rows and columns
	n = size(names,1);
	s = size(tab);
	m = s(2);

% Create header
	fprintf(fid,'\\begin{tabular}{l');
	for i = 1:m
		fprintf(fid,'c');
	end
	fprintf(fid,'}\n\\toprule\n');
	for i = 1:m+1
		if i == 1
			fprintf(fid,'%s',cell2mat(header(i)));
		else
			fprintf(fid,'&%s',cell2mat(header(i)));
		end
	end
	fprintf(fid,'\\\\\n\\midrule\n');

% Create middle
	for i = 1:n
		if str2num(cell2mat(names(i,1)))==1
			names_var = cell2mat(names(i,2));
			names_tab = cell2mat(names(i,3));
			precision = cell2mat(names(i,4));
			fprintf(fid,'%s',names_tab);
			for j = 1:m
                try
                    fprintf(fid,strcat('&',precision),table2array(tab(names_var,j)));
                catch
                    xx=1;
                end
			end
			fprintf(fid,'\\\\\n');
            
        elseif str2num(cell2mat(names(i,1)))==2
			fprintf(fid,'~');
			fprintf(fid,'\\\\\n');
		else
			fprintf(fid,'\\midrule\n');
			fprintf(fid,'\\multicolumn{%s}{c}{%s}',num2str(m+1),cell2mat(names(i,3)));
			fprintf(fid,'\\\\\n\\midrule\n');
		end
	end

% Create bottom
	fprintf(fid,'\\bottomrule\n\\end{tabular}\n');

% Close file
	fclose(fid);

end

